package com.common.app.helper

import android.os.Environment
import com.common.app.utls.SamplerObserver
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import okio.buffer
import okio.sink
import okio.source
import java.io.File
import java.io.IOException

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：界面跳转数据缓存传值
 * <p>
 * 修订历史：
 */
object ActivityStartHelper {

    private val rootPath =
        AppUtils.getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    private val compositeDisposable = ArrayList<Disposable>()

    private fun createDir(): File {
        return File("$rootPath/activity/")
    }

    private fun createFile(): File {
        return File("$rootPath/activity/file")
    }

    //保存集合数据到本地
    fun saveListData(list: List<Any>, listener: OnFileSaveSuccessListener) {
        compositeDisposable.clear()
        val content = JsonUtils.toJson(list)
        saveIo(content).observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : SamplerObserver<File>(compositeDisposable) {
                override fun onSucceed(data: File) {
                    listener.onSuccess(data.path)
                }
            })
    }

    //保存集合数据到本地
    fun readListData(listener: OnFileReadSuccessListener) {
        compositeDisposable.clear()
        readIoData(createFile()).observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : SamplerObserver<String>(compositeDisposable) {
                override fun onSucceed(data: String) {
                    listener.onSuccess(data)
                }
            })
    }

    private fun saveIo(content: String?): Observable<File> {
        val dir = createDir()
        val file = createFile()
        //创建文件夹目录
        if (!dir.exists()) {
            dir.mkdir()
        }
        //创建文件
        try {
            file.createNewFile()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return Observable.create { emitter ->
            try {
                file.sink().buffer().use { sink ->
                    content?.let {
                        sink.writeUtf8(it)
                    }
                }
                emitter.onNext(file)
            } catch (e: IOException) {
                emitter.onError(e)
            }
        }
    }

    private fun readIoData(file: File): Observable<String> {
        return Observable.create { emitter ->
            try {
                file.source().buffer().use { bufferedSource ->
                    var line: String?
                    val result = StringBuilder()
                    while (bufferedSource.readUtf8Line().also { line = it } != null) {
                        result.append(line)
                    }
                    emitter.onNext(result.toString())
                }
            } catch (e: IOException) {
                emitter.onError(e)
            }
        }
    }

    interface OnFileSaveSuccessListener {
        fun onSuccess(filePath: String)
    }

    interface OnFileReadSuccessListener {
        fun onSuccess(content: String)
    }

    fun onDestroy() {
        compositeDisposable.clear()
    }
}